<template>
  <div>
    <div class="case-detail-left">
      <a-form class="ant-advanced-search-form" :form="form" @submit="handleSubmit">
        <div class="repair-single-row">
          <a-col span="24" className="service-form">
            <a-form-item label="案例类型" class="repair-form"
                         :label-col="formItemLayout.labelCol"
                         :wrapper-col="formItemLayout.wrapperCol"
            >
              <a-select show-search option-filter-prop="children"
                        :class="[!showUpdateBtn ? 'input-disable':'']"
                        v-decorator="['caseType',
          { initialValue: detailData.caseType,
            rules: [{ required: true, message: '请选择案例类型' }] },
        ]"
                        placeholder="请选择案例类型"
              >
                <a-select-option value="故障案例">故障案例</a-select-option>
                <a-select-option value="调试案例">调试案例</a-select-option>
                <a-select-option value="工艺案例">工艺案例</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </div>
        <div class="repair-single-row">
          <a-col span="24" className="service-form">
            <a-form-item label="案例名称" class="repair-form"
                         :label-col="formItemLayout.labelCol"
                         :wrapper-col="formItemLayout.wrapperCol"
            >
              <a-input :class="[!showUpdateBtn ? 'input-disable':'']"
                       v-decorator="['caseName',
                  {
                    initialValue: detailData.caseName,
                    rules: [{ required: true, pattern: /\S/, message: '内容不能为空' }]
                    },
                ]"
                       placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
        </div>
        <div class="repair-single-row" style="display: none;">
          <a-col span="24" className="service-form">
            <a-form-item label="案例id" class="repair-form">
              <a-input  class="deploy-form-single-input" v-decorator="['caseId',
                  {
                    initialValue: detailData.id,
                    rules: [{ required: true, pattern: /\S/, message: '内容不能为空' }]
                    },
                ]"
                        placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
        </div>
        <div class="repair-single-row">
          <a-col span="24" className="service-form">
            <a-form-item label="适用范围" class="repair-form"
                         :label-col="formItemLayout.labelCol"
                         :wrapper-col="formItemLayout.wrapperCol"
            >
              <a-input :class="[!showUpdateBtn ? 'input-disable':'']"
                       v-decorator="['situation',
                  {
                    initialValue: detailData.situation,
                    rules: [{ required: true, pattern: /\S/, message: '内容不能为空' }]
                    },
                ]"
                       placeholder="请输入" autoComplete="off" />
            </a-form-item>
          </a-col>
        </div>
        <div class="repair-single-row">
          <a-col span="24" className="service-form">
            <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="工艺目标"
            >
              <a-textarea  :class="[!showUpdateBtn ? 'input-disable':'']"
                           v-decorator="['description',
          {
            initialValue: detailData.description,
            rules: [{ required: true, pattern: /\S/, message: '请输入' }] },
        ]"
                           placeholder="请输入" style="resize: none;"
              />
            </a-form-item>
          </a-col>
        </div>
        <div class="repair-single-solution-row">
          <a-row class="repair-single-row-row" v-for="(item, index) in solutionList" :key="item.id">
            <a-form-item class="middle-form-item"
                         :label-col="textAreaItemLayout.labelCol"
                         :wrapper-col="textAreaItemLayout.wrapperCol"
                         label="解决方案"
            >
              <a-textarea :class="[!showUpdateBtn ? 'input-disable':'']"
                          v-decorator="[`solutionContent[${index}].solution`,
          { initialValue: item.solution,
            rules: [{ required: true, pattern: /\S/, message: '请输入解决方案' }] },
        ]"
                          placeholder="请输入解决方案" style="resize: none" :readOnly="isReadOnly"
              />
            </a-form-item>
            <a-form-item style="display: none">
              <a-textarea
                v-decorator="[`solutionContent[${index}].id`,
          { initialValue: item.id },
        ]"
              />
            </a-form-item>
            <div class="upload-container" @click.prevent="updateFileIndex(index)">
              <span class="upload-title">图片:</span>
              <a-upload
                :class="[!showUpdateBtn ? 'picture-disable':'']"
                :action="item.action"
                name="files"
                list-type="picture-card"
                :file-list="item.fileList"
                @preview="handlePreview"
                @change="handleChange"
              >
                <div v-if="item.fileList.length < 5 && showUpdateBtn">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">图 片</div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </div>
          </a-row>
        </div>
        <div class="repair-single-row">
          <span class="upload-title">案例标签:</span>
          <a-form-item :wrapper-col="{ span: 24, offset: 0 }">
            <tag-container @tagChange="getChildTag"
                           :tags="tags" :showUpdateBtn="showUpdateBtn">
            </tag-container>
          </a-form-item>
        </div>
        <div class="repair-single-row" v-show="showUpdateBtn">
          <a-form-item :wrapper-col="{ span: 24, offset: 0 }" class="bottom-submit">
            <a-button  :class="[showUpdateBtn ? 'submit-button':'submit-button-hide']"
                       type="primary" html-type="submit" :disabled="isDisabled">提 交</a-button>
          </a-form-item>
        </div>

        <div class="bottom-amendment-submit" v-show="showPassBtn && (roleId === 17 || roleId === 19)">
          <a-button type="primary" class="amendment-pass" @click="amendmentPass">方案通过</a-button>
          <a-button type="danger" class="amendment-not-pass" @click="amendmentNotPass">方案不通过</a-button>
        </div>

      </a-form>
    </div>
    <div class="case-detail-right">
      <a-button type="primary"
                :class="[(showPassBtn && (roleId === 17 || roleId === 19)) ? 'detail-update-button':'detail-update-hide']"
                @click="handleUpdate">修 改</a-button>
    </div>
  </div>

</template>

<script>
  import { mapState, mapMutations } from 'vuex'
  import api from '@/server/userConfig';
  import GLOBAL from "@/api/global_variable"
  import TagContainer from './components/tagContainer'
  export default {
    name: "CaseDetail",
    components: {
      TagContainer
    },
    computed: {
      ...mapState(['roleId'])
    },
    data () {
      return {
        showUpdateBtn: false,
        showPassBtn: true,
        isReadOnly: true,
        username: '',
        detailData: {},
        solutionList: [],
        fileIndex: 0,
        previewVisible: false,
        previewImage: '',
        tags: [],
        caseId: 0,
        isDisabled: false,
        formItemLayout: {
          labelCol: { span: 4 },
          wrapperCol: { span: 15 },
        },
        formMiddleItemLayout: {
          labelCol: { span: 4 },
          wrapperCol: { span: 15 },
        },
        textAreaItemLayout: {
          labelCol: { span: 4 },
          wrapperCol: { span: 20 },
        },
        form: this.$form.createForm(this, { name: 'validate_other' })
      }
    },
    methods: {
      getLocalStorageData () {
        const phone = localStorage.getItem('phone');
        if (!phone) {
          this.$router.push('/');
        }
        this.username = phone;
      },
      // 点击修改;
      handleUpdate () {
        this.showUpdateBtn = true;
        this.showPassBtn = false;
        this.isReadOnly = false;
      },
      // 点击方案通过;
      amendmentPass () {
        this.$Modal.confirm({
          title: '确定方案通过吗?',
          content: '',
          okText: '确定',
          cancelText: '取消',
          onOk: async () => {
            const result = await api.reqAmendmentPass({
              id: this.caseId,
              approval: false,
              checkPerson: this.username,
            });
            console.log(result);
            if (result.MsgCode === 0) {
              setTimeout(() => {
                this.$Modal.success({
                  title: '',
                  content: '审核通过!',
                  okText: '确定',
                  onOk: () => {
                    window.location.reload();
                  }
                });
              }, 300)
            }
          },
          onCancel () {}
        });
      },
      // 点击方案不通过;
      amendmentNotPass () {
        this.$Modal.confirm({
          title: '确定审核不通过吗?',
          content: '',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk: async () => {
            const result = await api.reqAmendmentPass({
              id: this.caseId,
              approval: true,
              checkPerson: this.username,
            });
            console.log(result);
            if (result.MsgCode === 0) {
              this.$message.success('审核未通过!');
            }
          },
          onCancel () {}
        });
      },
      // 获取案例详情;
      async getDetail (id) {
        const res = await api.reqGetCaseDetail({id: id});
        console.log(res);
        if (res.MsgCode !== 0) {
          return;
        }
        if (res.Data.approval === 1) {
          // 通过后，不用再显示;
          this.showPassBtn = false;
        } else {
          this.showPassBtn = true;
        }
        let solution = res.Data.solution;
        let solutionList = [];
        const solutionLength = solution.length;
        const tagString = res.Data.tags.slice(0, res.Data.tags.length - 1);
        const tagArray = tagString.split(',');
        for (let i = 0; i < solutionLength; i++) {
          solutionList.push({
            id: solution[i].id,
            solution: solution[i].solution,
            fileList: [],
            action: GLOBAL.hncWebIp + "/uploadSolutionPicture.action?pictureType=" + (i * 10 + 1) +
            "&pictureNumber=" + (i * 10 + 1),
          });
          for (let j = 0; j < solution[i].picture.length; j++) {
            solutionList[i].fileList.push({
              id: solution[i].picture[j].id,
              uid: -j,
              name: 'image.png',  //超级bug，这个name必须有，而且不能为空;
              status: 'done', // 状态有：uploading done error removed
              pictureNumber: solution[i].picture[j].pictureNumber,
              solutionId: solution[i].picture[j].solutionId,
              url: GLOBAL.imgDownUrl + solution[i].picture[j].pictureUrl
            })
          }
        }
        this.solutionList = solutionList;
        this.detailData = res.Data;
        this.tags = tagArray;
        console.log(this.detailData);
      },
      // 获取上传图片的索引;
      updateFileIndex (index) {
        this.fileIndex = index
      },
      getChildTag (tags) {
        this.tags = tags;
      },
      // 提交修改;
      handleSubmit (e) {
        e.preventDefault();
        this.form.validateFields( async (err, values) => {
          if (!err) {
            //console.log(values);
            //console.log(this.tags);
            let submitCaseData = {};
            submitCaseData.caseType = values.caseType;
            submitCaseData.caseName = values.caseName;
            submitCaseData.situation = values.situation;
            submitCaseData.description = values.description;
            submitCaseData.id = values.caseId;
            submitCaseData.username = this.username;
            submitCaseData.caseTag = this.tags;
            let solution = [];
            const solutionContent = values.solutionContent;
            const solutionListLength = this.solutionList.length;
            const solutionList = this.solutionList;
            for (let i = 0; i < solutionListLength; i++) {
              solutionList[i].pictureId = '';
              for (let j = 0; j < solutionList[i].fileList.length; j++) {
                if (solutionList[i].fileList.length === 0) {
                  solutionList[i].pictureId = '';
                  return;
                } else {
                  solutionList[i].pictureId += solutionList[i].fileList[j].id + ',';
                }
              }
              solutionList[i].pictureId = solutionList[i].pictureId.slice(0, solutionList[i].pictureId.length - 1);
              if(solutionContent[i].id === solutionList[i].id) {
                solutionList[i].item = solutionContent[i].solution;
              }
              solution.push({
                item: solutionList[i].item,
                step: i,
                pictureId: solutionList[i].pictureId || 0
              })
            }
            submitCaseData.solution = solution;
            const jsonSubmitCaseData = JSON.stringify(submitCaseData);
            console.log(jsonSubmitCaseData);
            // 数据组装完成, 发送到后台;
            api.reqUpdateCase(jsonSubmitCaseData).then((res) => {
              console.log(res);
              if (res.MsgCode === 0) {
                this.showUpdateBtn = false;
                this.$Modal.success({
                  title: '',
                  content: '修改成功!',
                  okText: '确定',
                  onOk: () => {
                    window.location.reload();
                  }
                })
              }
            });
            const res = await api.reqUpdateCase(jsonSubmitCaseData);
            console.log(res);
            if (res.MsgCode === 0) {
              this.showUpdateBtn = false;
              this.$Modal.success({
                title: '',
                content: '修改成功!',
                okText: '确定',
                onOk: () => {
                  window.location.reload();
                }
              })
            }
          }
        })
      },
      async handlePreview (file) {
        console.log(file);
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        this.previewImage = file.url || file.preview;
        this.previewVisible = true;
      },
      handleCancel () {
        this.previewVisible = false;
      },
      handleChange ({file, fileList}) {
        if (file.status === 'uploading') {
          this.solutionList[this.fileIndex].fileList = fileList;
        }
        else if (file.status === 'done') {
          this.solutionList[this.fileIndex].fileList = fileList;
          file = fileList[fileList.length - 1];
          // 取出响应数据中的图片文件名和url
          const { id, url, pictureType } = file.response.Data[0];
          // 保存到上传的file对象
          file.id = id;
          file.pictureType = pictureType;
          file.url = GLOBAL.imgDownUrl + url;
          //console.log(file);
          //console.log(fileList);
          //console.log(this.solutionList);
        } else if (file.status === 'removed') {
          this.$Modal.confirm({
            title: '确定删除此图片吗?',
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
              const result = await api.reqDeleteSingleImg({id: file.id});
              console.log(result);
              if (result.MsgCode === 0) {
                this.$message.success('删除成功!');
              }
              this.solutionList[this.fileIndex].fileList = fileList;
              //console.log(this.solutionList);
            },
            onCancel () {}
          });
        }
      },
    },
    mounted () {
      this.getLocalStorageData();
      console.log(this.roleId);
      const id = this.$route.params.id;
      this.caseId = this.$route.params.id;
      // 根据id获取案例详情;
      this.getDetail(id);
    }
  }
</script>

<style scoped="scoped">
  @import "./components/style.css";
</style>
